package com.gopay.bis.cib.ebank.operation;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cib.ebank.CibMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MD5Util;
import com.gopay.remote.bank.ICertHelper;

/**
 * 兴业银行B2B签名验签类
 * 
 * @CibB2bCertHelper.java
 * @author zhengxue
 * @2014-11-21 下午2:54:46 www.gopay.com.cn Inc.All rights reserved.
 */
public class CibB2bCertHelper implements ICertHelper {

    public String sign(BaseMessage baseMessage) throws GopayException {
        try {
            CibMessage messageB2B = (CibMessage) baseMessage;
            BankLogUtils.printB2BSignPlainLog(messageB2B);
            // 银行MAC要大写
            String signature = MD5Util.sign(messageB2B.getPlainMessage()).toUpperCase();
            BankLogUtils.printB2BSignSignatureLog(messageB2B, signature);
            return signature;
        } catch (Exception e) {
            BankLogUtils.printB2BSignExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6028);
        }
    }

    public Object verify(BaseMessage baseMessage) throws GopayException {
        try {
            CibMessage messageB2B = (CibMessage) baseMessage;
            boolean isVerify;
            BankLogUtils.printB2BVerifyPlainLog(messageB2B);
            messageB2B.setSignMessage(messageB2B.getMac());
            BankLogUtils.printB2BVerifySignatureLog(messageB2B);
            // 银行MAC要大写
            String signature = MD5Util.sign(messageB2B.getPlainMessage()).toUpperCase();
            if (signature.equals(messageB2B.getMac())) {
                // 验签成功
                isVerify = true;
                BankLogUtils.printB2BVerifyResultLog(messageB2B, isVerify);
            } else {
                // 验签失败
                isVerify = false;
                BankLogUtils.printB2BVerifyResultLog(messageB2B, isVerify);
            }
            return isVerify;
        } catch (Exception e) {
            BankLogUtils.printB2CVerifyExceptionLog(baseMessage, e);
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6030);
        }
    }

}
